<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>test</title>

    <script type="text/javascript">
        let websocket = null;
        //判断当前浏览器是否支持WebSocket
        if (!('WebSocket' in window)) {
            alert('Not support websocket')
        }

        function connect() {
            //连接WebSocket节点
            let userId = document.getElementById('con').value;
            websocket = new WebSocket('ws://localhost/user/websocket/' + userId);
            //连接发生错误的回调方法
            websocket.onerror = function () {
                setMessageInnerHTML("error");
            };
            //连接成功建立的回调方法
            websocket.onopen = function () {
                setMessageInnerHTML("open");
            };
            //接收到消息的回调方法
            websocket.onmessage = function (event) {
                setMessageInnerHTML(event.data);
            };
            //连接关闭的回调方法
            websocket.onclose = function () {
                setMessageInnerHTML("close");
            };
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            websocket.close();
        };

        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            document.getElementById('msg').innerHTML += innerHTML + '<br/>';
        }

        //关闭连接
        function closeWebSocket() {
            websocket.close();
        }

        //发送消息
        function send() {
            let content = document.getElementById('seo').value;
            websocket.send(content);
        }
    </script>
</head>
<body>
<label for="con">用户id</label><input id="con" type="text"/>
<button onclick="connect()">connect</button>
<br>
<br>
<label for="seo">发消息</label><input id="seo" type="text"/>
<button onclick="send()">Send</button>
<br>
<br>
<button onclick="closeWebSocket()">关闭连接</button>
<br>
<div id="msg"></div>
</body>

</html>